//
//  ConversationManager.m
//  AAIM
//
//  Created by awh on 2019/12/23.
//  Copyright © 2019年 AAIM. All rights reserved.
//

#import "ConversationManager.h"

#import "ConversationListDataBase.h"

#import "BTMessageModel.h"
@interface ConversationManager ()

@property(nonatomic, strong) NSMutableArray<BTMessageModel *> *conversations;

@end

@implementation ConversationManager

static ConversationManager *manager = nil;
+ (instancetype)shareManager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[self alloc] init];
    });
    return manager;
}


- (instancetype)init {
    if (self = [super init]) {
        [self reloadData];
    }
    return self;
}

// 从数据库重新加载数据
- (void)reloadData {
    NSArray *array = [[ConversationListDataBase shareConversationListDataBase] queryAllConversations];
    _conversations = [NSMutableArray arrayWithArray:array];
}

// 保存会话
- (void)saveConversation:(BTMessageModel *)msg {
    msg.keyid = [self keyidOfMessage:msg];
    if (msg.chatType == ChatTypeFriend || msg.chatType == ChatTypeGroup) {
        BTMessageModel *origin = [self originExistConversation:msg];
        if (!origin) { // 新的会话
            [self.conversations addObject:msg];
        } else { // 已存在的会话
            if (origin.timestamp < msg.timestamp || msg.messageType == MessageTypeRecall) {
                msg.unreadCount += origin.unreadCount;
                msg.offlineUnreadCount += origin.offlineUnreadCount;
                msg.isAt = origin.isAt ? YES : NO;
                BOOL isAt = [msg.msg containsString:kAtDividedSymbols];
                if (isAt) {
                    msg.isAt = [self isAtSelf:msg.msg] || [self isAtSelf:origin.msg];
                };
                msg.ignore=origin.ignore;
                msg.top=origin.top;
                [self.conversations addObject:msg];
            } else {
                origin.unreadCount += msg.unreadCount;
                origin.offlineUnreadCount += msg.offlineUnreadCount;
                if (!origin.isAt) {
                    BOOL isAt = [msg.msg containsString:kAtDividedSymbols];
                    origin.isAt = isAt;
                }
                [self.conversations addObject:origin];
            }
        }
    }else
    {
        //通知
        BTMessageModel *origin = [self originExistConversation:msg];
        if (!origin) { // 新的会话
            [self.conversations addObject:msg];
        } else
        {
            [self.conversations addObject:msg];
        }
    }
    
}

// 查找当前登录用户的全部会话
- (NSArray<BTMessageModel *> *)queryAllConversations {
//    long long fromTime = [ChatTool shareChatTool].currentTimestamp - 3 * 60 * 60 * 1000;
    for (BTMessageModel *obj in self.conversations) {
//        if (obj.updateTimestamp != 0 && obj.updateTimestamp < fromTime) {
//            obj.msgtype = MessageTypeText;
//            obj.content = @"";
//            obj.unreadCount = obj.offlineUnreadCount = 0;
//        }
    }
    return [self sortedConversations];
}

// 查询未读消息数
- (NSInteger)totalUnreadCount {
    NSInteger count = 0;
    for (BTMessageModel *obj in self.conversations) {
        if (!obj.ignore) {
            count += (obj.unreadCount + obj.offlineUnreadCount);
        }
    }
    return count;
    
    //    __block NSInteger total = 0;
    //    [self.conversations enumerateObjectsUsingBlock:^(BTMessageModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    //        if (!obj.ignore) {
    //            NSArray<NSString *> *conponents = [obj.keyid componentsSeparatedByString:@"_"];
    //            if (conponents.count == 2) {
    //                NSInteger type = [conponents[0] isEqualToString:@"friend"] ? 1 : 2;
    //                NSInteger friendOrGroupId = conponents[1].integerValue;
    //                BOOL isIn = [[LoginManager shareLoginManager].userDataBase isAlreadyHaveUserOrGroupWithID:friendOrGroupId istype:type];
    //                if (isIn) {
    //                    total += (obj.unreadCount + obj.offlineUnreadCount);
    //                }
    //            }
    //        }
    //    }];
    //    return total;
}

// 根据时间戳清空该消息的未读消息数
- (void)clearUnreadCount:(BTMessageModel *)msg {
    NSString *keyid = [self keyidOfMessage:msg];
    msg.keyid = keyid;
    for (BTMessageModel *obj in self.conversations) {
        if ([obj.keyid isEqualToString:keyid]) {
            obj.unreadCount = 0;
            obj.offlineUnreadCount = 0;
            break;
        }
    }
}

// 删除会话
- (void)deleteConversationWithKeyid:(NSString *)keyid {
    for (BTMessageModel *obj in self.conversations) {
        if ([obj.keyid isEqualToString:keyid]) {
            [self.conversations removeObject:obj];
            break;
        }
    }
}



#pragma mark - private methods

- (NSArray *)sortedConversations {
    if (self.conversations == nil || self.conversations.count == 0) return nil;
    
    NSMutableArray *sorteds = [NSMutableArray new];
    NSMutableArray *temps = [NSMutableArray new];
//    ContactorModel *serviceModel = [[LoginManager shareLoginManager].userDataBase ReadCustomerServiceData];
//    NSInteger service = serviceModel.user_id.integerValue;
    for (BTMessageModel *obj in self.conversations) {
//        if (obj.uid == service) {
//            [sorteds addObject:obj];
//        } else {
            [temps addObject:obj];
//        }
    }
    NSSortDescriptor *topSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"top" ascending:NO];
    NSSortDescriptor *topTimestampSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"topTimestamp" ascending:NO];
    NSSortDescriptor *timestampSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"timestamp" ascending:NO];
    NSArray *tempConversationsSorted = [temps sortedArrayUsingDescriptors:@[topSortDescriptor, topTimestampSortDescriptor, timestampSortDescriptor]];
    if (tempConversationsSorted != nil && tempConversationsSorted.count > 0) {
        [sorteds addObjectsFromArray:tempConversationsSorted];
    }
    return sorteds;
    
}

// 查找已存在的会话
- (BTMessageModel *)originExistConversation:(BTMessageModel *)msg {
    NSString *keyid = [self keyidOfMessage:msg];
    __block BTMessageModel *origin = nil;
    for (BTMessageModel *obj in self.conversations) {
        if ([obj.keyid isEqualToString:keyid]) {
            origin = obj;
            [self.conversations removeObject:obj];
            break;
        }
    }
    return origin;
}
// 会话主键id
- (NSString *)keyidOfMessage:(BTMessageModel *)msg {
    NSString *keyid = @"";
    if (msg.messageDirection == MessageDirectionSend) {
        if (msg.chatType==ChatTypeFriend){
            keyid = [NSString stringWithFormat:@"friend_%@", msg.rfuuid];
        } else {
            keyid = [NSString stringWithFormat:@"group_%@", msg.gId];
        }
    } else {
        if (msg.chatType==ChatTypeFriend){
            if ([NSObject ldy_isEmpty:msg.f_uuid]) {
                keyid = [NSString stringWithFormat:@"friend_%@", msg.fuuid];
            }else
            {
                keyid = [NSString stringWithFormat:@"friend_%@", msg.f_uuid];
            }
        } else if (msg.chatType==ChatTypeGroup) {
            keyid = [NSString stringWithFormat:@"group_%@", msg.gId];
        } else if (msg.chatType==ChatTypeSystem) {
            if (msg.receiveUid==0) {
                if (msg.groupId==0) {
                    keyid=msg.keyid;
                }else
                {
                    keyid = [NSString stringWithFormat:@"sys_%ld", msg.groupId];
                }
            }else
            {
                if (msg.groupId==0) {
                    keyid = [NSString stringWithFormat:@"sys_%ld", msg.receiveUid];
                }else
                {
                    keyid=msg.keyid;
                }
            }
//            keyid = [NSString stringWithFormat:@"sys_%ld", msg.receiveUid];
        }
    }
    return keyid;
}
// 判断是否被@
- (BOOL)isAtSelf:(NSString *)content {
    BOOL isAtMsg = [content containsString:kAtDividedSymbols];
    if (!isAtMsg) {
        return NO;
    }
    NSArray<NSString *> *components = [content componentsSeparatedByString:kAtDividedSymbols];
    NSString *idsStr = components[1];
    __block BOOL isAtSelf = NO;
    if ([idsStr isEqualToString:kAtAllSymbols]) {
        isAtSelf = YES;
    } else {
        NSArray<NSString *> *ids = [idsStr componentsSeparatedByString:@","];
        [ids enumerateObjectsUsingBlock:^(NSString * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            NSInteger uid = obj.integerValue;
            if (uid == [LoginManager shareLoginManager].userModel.fuuid.integerValue) {
                isAtSelf = YES;
                *stop = YES;
            }
        }];
    }
    return isAtSelf;
}

@end
